package com.seeyon.apps.ext.ObxMsgPush.eventlisteners;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.logging.log4j.util.Strings;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.cip.binding.manager.ThirdpartyUserMapperManager;
import com.seeyon.apps.cip.manager.RegisterManager;
import com.seeyon.apps.ext.ObxMsgPush.manager.ObxPushOtherMessageManager;
import com.seeyon.apps.ext.ObxMsgPush.service.AppService;
import com.seeyon.apps.ext.ObxMsgPush.service.ResService;
import com.seeyon.apps.ext.ObxMsgPush.utils.HttpUtil;
import com.seeyon.apps.ext.ObxMsgPush.utils.MyUtils;
import com.seeyon.client.CTPRestClient;
import com.seeyon.client.CTPServiceClientManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.organization.bo.V3xOrgAccount;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.bo.V3xOrgPost;
import com.seeyon.ctp.organization.event.AddDepartmentEvent;
import com.seeyon.ctp.organization.event.AddMemberEvent;
import com.seeyon.ctp.organization.event.DeleteDepartmentEvent;
import com.seeyon.ctp.organization.event.DeleteMemberEvent;
import com.seeyon.ctp.organization.event.UpdateDepartmentEvent;
import com.seeyon.ctp.organization.event.UpdateMemberEvent;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import com.seeyon.ctp.util.annotation.ListenEvent;

public class OrganizationEvent{
	
	private static final Log log = CtpLogFactory.getLog(OrganizationEvent.class);
	static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
	private static   OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
	private static ThirdpartyUserMapperManager thirdpartyUserMapperManager = (ThirdpartyUserMapperManager) AppContext.getBean("thirdpartyUserMapperManager");
	private static RegisterManager registerManager = (RegisterManager) AppContext.getBean("registerManager");
	private static final String TOKENURH=AppContext.getSystemProperty("auth.tokenurl");//OA tokenurl
	private static final String EID=AppContext.getSystemProperty("auth.eid");//云之家 团队EID
	private static final String APPID=AppContext.getSystemProperty("auth.appid");//云之家 appid
	private static final String APPSECRET=AppContext.getSystemProperty("auth.appsecret");//云之家 App Secret
	private static final String SIGNKEY=AppContext.getSystemProperty("auth.signkey");//云之家 Sign Key
	private static final String TXLMY=AppContext.getSystemProperty("auth.txlmy");//云之家 通讯录同步可编辑密钥
	private static final String OAAPPCODE=AppContext.getSystemProperty("auth.oaappcode");//OA应用编号
	private static ObxPushOtherMessageManager jdMessageManager = (ObxPushOtherMessageManager) AppContext.getBean("jdMessageManager");
	private static  OrgManagerDirect orgManagerDirect = (OrgManagerDirect) AppContext.getBean("orgManagerDirect");
	
	public static OrgManagerDirect getOrgManagerDirect() {
		return orgManagerDirect;
	}
	public static void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
		OrganizationEvent.orgManagerDirect = orgManagerDirect;
	}
	public static ObxPushOtherMessageManager getJdMessageManager() {
		return jdMessageManager;
	}
	public static void setJdMessageManager(ObxPushOtherMessageManager jdMessageManager) {
		OrganizationEvent.jdMessageManager = jdMessageManager;
	}
	public static OrgManager getOrgManager() {
		return orgManager;
	}
	public static void setOrgManager(OrgManager orgManager) {
		OrganizationEvent.orgManager = orgManager;
	}
	public static ThirdpartyUserMapperManager getThirdpartyUserMapperManager() {
		return thirdpartyUserMapperManager;
	}
	public static void setThirdpartyUserMapperManager(ThirdpartyUserMapperManager thirdpartyUserMapperManager) {
		OrganizationEvent.thirdpartyUserMapperManager = thirdpartyUserMapperManager;
	}
	public static RegisterManager getRegisterManager() {
		return registerManager;
	}
	public static void setRegisterManager(RegisterManager registerManager) {
		OrganizationEvent.registerManager = registerManager;
	}

	
	private static   ResService resService = (ResService) AppContext.getBean("resService");
	private static   AppService appService = (AppService) AppContext.getBean("appService");
	
	public static ResService getResService() {
		return resService;
	}
	public static void setResService(ResService resService) {
		OrganizationEvent.resService = resService;
	}
	
	public static AppService getAppService() {
		return appService;
	}
	public static void setAppService(AppService appService) {
		OrganizationEvent.appService = appService;
	}
	/**
	 * 新增人员监听
	 * @param event
	 * @throws Exception 
	 */
	@ListenEvent(event= AddMemberEvent.class,async=true)
    public void onAddMember(AddMemberEvent event) throws Exception{
		log.info("进入人员新增！");
		String accessToken = resService.getToken();
    	log.info("accessToken:"+accessToken);
        V3xOrgMember member = event.getMember();
        String telNumber = member.getTelNumber();
        if(Strings.isNotBlank(telNumber)) {
        	 JSONArray deptarray = MyUtils.getOrgDepartments(member.getOrgAccountId().toString());
             V3xOrgAccount account = orgManager.getAccountById(member.getOrgAccountId());
     		log.info("部门回参："+deptarray.toString());
     		JSONObject jsonObject = new JSONObject();
     		for(int i=0;i<deptarray.size();i++) {
     			log.info("===========================================");
     			String wholeName = deptarray.getJSONObject(i).getString("wholeName");
     			log.info("当前wholeName："+wholeName);
     			wholeName=account.getName()+"\\"+wholeName.replace(",", "\\");
     			log.info("处理后wholeName："+wholeName);
     			log.info("===========================================");
     			jsonObject.put(deptarray.getJSONObject(i).getString("path"), wholeName);
     		}
             JSONObject object = new JSONObject();
     		object.put("name", member.getName());//姓名
     		JSONObject data = new JSONObject();
     		data.put("mobile",member.getTelNumber());
     		data.put("email", "");
     		data.put("password", "");
     		object.put("account", data);//
     		object.put("phone", member.getTelNumber());//手机电话
     		object.put("isHidePhone", 0);//可选,是否在通讯录中隐藏手机号码,0: 不隐藏; 1: 隐藏,默认为0
     		V3xOrgDepartment department= orgManager.getDepartmentById(member.getOrgDepartmentId());
     		String wholeName = jsonObject.getString(department.getPath());
     		log.info("取到的wholeName："+wholeName);
     		log.info("===========================================");
     		object.put("department", wholeName);//可选, 部门长名称，格式："一级部门\\二级部门\\三级部门"，如 ： "研发中心\\移动平台产品部\\开发部"，挂在根部门下面，直接传： "\\"
     		V3xOrgPost orgPost= orgManager.getPostById(member.getOrgPostId());
     		object.put("jobTitle", orgPost.getName());//可选,职位,默认为空
     		object.put("jobNo", member.getCode());//企业工号
     		if(member.getGender()!=-1) {
     			object.put("gender", member.getGender());//可选,性别,0: 不确定; 1: 男; 2: 女,默认为0
     		}else {
     			object.put("gender", 0);//可选,性别,0: 不确定; 1: 男; 2: 女,默认为0
     		}
     		if(member.getBirthday()!=null) {
     			object.put("birthday",dateFormat.format(member.getBirthday()));//可选,生日
     		}
     		if(member.getEnabled()) {
     			object.put("status", 1);//可选,状态 0: 注销，1: 正常，2: 禁用,默认为1
     		}else {
     			object.put("status", 2);//可选,状态 0: 注销，1: 正常，2: 禁用,默认为1
     		}
     		object.put("weights", member.getSortId());//可选，排序权重，权重越小，排序越前.
//     		object.put("orgUserType", 0);//可选,是否部门负责人,0表示普通用户，1表示部门负责人***
     		object.put("contact", new JSONArray());//
//     		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//     		if(member.getHiredate()!=null) {
//     			object.put("hireDate", simpleDateFormat.format(dateFormat.format(member.getHiredate())));//入职日期，格式如："2018-01-01"
//     		}
//     		object.put("positiveDate", "");//转正日期，格式如："2018-01-01"
     		object.put("regSource", "K3OA");//
     		object.put("identityId", member.getIdNum());//身份证号，必须为正确的身份证格式
     		log.info("准备推送object："+object.toString());
     		JSONArray jsonArray = new JSONArray();
     		jsonArray.add(object);
     		JSONObject backObject = new JSONObject();
     		backObject.put("persons", jsonArray);
     		log.info("data："+backObject.toString());
     		log.info("backObject"+backObject.toString());
     		String url="https://yunzhijia.com/gateway/openimport/open/person/add?accessToken="+accessToken;//新增人员
     		Map<String, String> params=new HashMap<String, String>();
     		params.put("eid", EID);
     		params.put("data", backObject.toString());
     		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
     		log.info("params:"+JSONObject.toJSONString(params));
     		String sendByHttp = HttpUtil.sendPost(url, params);
     		log.info("调用后回参:"+sendByHttp);
     		String setThirdpartyUser = MyUtils.SetThirdpartyUser(sendByHttp);
     		log.info("匹配后回参:"+setThirdpartyUser);
        }else {
        	log.info("电话为空跳过！");
        }
       
    }
	/**
	 * 查询后存在修改云之家人员信息
	 * @param member
	 * @param openId
	 * @param accessToken
	 * @param jsonObject
	 * @throws Exception
	 */
	public void uptMember(V3xOrgMember member,String openId,String accessToken,JSONObject jsonObject) throws Exception{
		JSONObject object = new JSONObject();
        object.put("openId",openId);//必填,人员的openId
		object.put("name", member.getName());//姓名
		object.put("phone", member.getTelNumber());//手机电话
		object.put("isHidePhone", 0);//可选,是否在通讯录中隐藏手机号码,0: 不隐藏; 1: 隐藏,默认为0
		V3xOrgDepartment department= orgManager.getDepartmentById(member.getOrgDepartmentId());
		String wholeName = jsonObject.getString(department.getPath());
		log.info("取到的wholeName："+wholeName);
		log.info("===========================================");
		object.put("department", wholeName);//可选, 部门长名称，格式："一级部门\\二级部门\\三级部门"，如 ： "研发中心\\移动平台产品部\\开发部"，挂在根部门下面，直接传： "\\"
		V3xOrgPost orgPost= orgManager.getPostById(member.getOrgPostId());
		object.put("jobTitle", orgPost.getName());//可选,职位,默认为空
		object.put("jobNo", member.getCode());//企业工号
		if(member.getGender()!=-1) {
			object.put("gender", member.getGender());//可选,性别,0: 不确定; 1: 男; 2: 女,默认为0
		}else {
			object.put("gender", 0);//可选,性别,0: 不确定; 1: 男; 2: 女,默认为0
		}
		if(member.getBirthday()!=null) {
			object.put("birthday",dateFormat.format(member.getBirthday()));//可选,生日
		}
		if(member.getEnabled()) {
			object.put("status", 1);//可选,状态 0: 注销，1: 正常，2: 禁用,默认为1
			log.info("启用");
			updateStatus(openId,"4",accessToken);
		}else {
			log.info("禁用");
			updateStatus(openId,"3",accessToken);
		}
		object.put("weights", member.getSortId());//可选，排序权重，权重越小，排序越前.
//		object.put("orgUserType", 0);//可选,是否部门负责人,0表示普通用户，1表示部门负责人***
		object.put("contact", new JSONArray());//
//		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//		if(member.getHiredate()!=null) {
//			object.put("hireDate", simpleDateFormat.format(dateFormat.format(member.getHiredate())));//入职日期，格式如："2018-01-01"
//		}
//		object.put("positiveDate", "");//转正日期，格式如："2018-01-01"
		object.put("regSource", "K3OA");//
		object.put("identityId", member.getIdNum());//身份证号，必须为正确的身份证格式
		log.info("准备推送object："+object.toString());
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(object);
		JSONObject backObject = new JSONObject();
		backObject.put("persons", jsonArray);
		log.info("data："+backObject.toString());
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/person/updateInfo?accessToken="+accessToken;//修改人员
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
		SetThirdpartyUser(openId,member.getTelNumber());
	}
	/**
	 * 查询后没有新增云之家人员信息
	 * @param member
	 * @param openId
	 * @param accessToken
	 * @param jsonObject
	 * @throws Exception
	 */
	public void addMember(V3xOrgMember member,String accessToken,JSONObject jsonObject) throws Exception{
		JSONObject object = new JSONObject();
		object.put("name", member.getName());//姓名
		JSONObject data = new JSONObject();
		data.put("mobile",member.getTelNumber());
		data.put("email", "");
		data.put("password", "");
		object.put("account", data);//
		object.put("phone", member.getTelNumber());//手机电话
		object.put("isHidePhone", 0);//可选,是否在通讯录中隐藏手机号码,0: 不隐藏; 1: 隐藏,默认为0
		V3xOrgDepartment department= orgManager.getDepartmentById(member.getOrgDepartmentId());
		String wholeName = jsonObject.getString(department.getPath());
		log.info("取到的wholeName："+wholeName);
		log.info("===========================================");
		object.put("department", wholeName);//可选, 部门长名称，格式："一级部门\\二级部门\\三级部门"，如 ： "研发中心\\移动平台产品部\\开发部"，挂在根部门下面，直接传： "\\"
		V3xOrgPost orgPost= orgManager.getPostById(member.getOrgPostId());
		object.put("jobTitle", orgPost.getName());//可选,职位,默认为空
		object.put("jobNo", member.getCode());//企业工号
		if(member.getGender()!=-1) {
			object.put("gender", member.getGender());//可选,性别,0: 不确定; 1: 男; 2: 女,默认为0
		}else {
			object.put("gender", 0);//可选,性别,0: 不确定; 1: 男; 2: 女,默认为0
		}
		if(member.getBirthday()!=null) {
			object.put("birthday",dateFormat.format(member.getBirthday()));//可选,生日
		}
		if(member.getEnabled()) {
			object.put("status", 1);//可选,状态 0: 注销，1: 正常，2: 禁用,默认为1
		}else {
			object.put("status", 2);//可选,状态 0: 注销，1: 正常，2: 禁用,默认为1
		}
		object.put("weights", member.getSortId());//可选，排序权重，权重越小，排序越前.
//			object.put("orgUserType", 0);//可选,是否部门负责人,0表示普通用户，1表示部门负责人***
		object.put("contact", new JSONArray());//
//			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//			if(member.getHiredate()!=null) {
//				object.put("hireDate", simpleDateFormat.format(dateFormat.format(member.getHiredate())));//入职日期，格式如："2018-01-01"
//			}
		object.put("positiveDate", "");//转正日期，格式如："2018-01-01"
		object.put("regSource", "K3OA");//
		object.put("identityId", member.getIdNum());//身份证号，必须为正确的身份证格式
		log.info("准备推送object："+object.toString());
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(object);
		JSONObject backObject = new JSONObject();
		backObject.put("persons", jsonArray);
		log.info("data："+backObject.toString());
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/person/add?accessToken="+accessToken;//新增人员
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
		String setThirdpartyUser = MyUtils.SetThirdpartyUser(sendByHttp);
		log.info("匹配后回参:"+setThirdpartyUser);
	}
	/**
	 * 修改人员监听
	 * @param event
	 * @throws Exception 
	 */
	@ListenEvent(event= UpdateMemberEvent.class,async=true)
	public void onUpdateMember(UpdateMemberEvent event) throws Exception{
		log.info("进入人员修改！");
		String accessToken = resService.getToken();
    	log.info("accessToken:"+accessToken);
    	V3xOrgMember member = event.getMember();//新的member
		String telNumber = member.getTelNumber();
		V3xOrgMember oldMember = event.getOldMember();
		String oldtelNumber = oldMember.getTelNumber();
		if(Strings.isNotBlank(telNumber)) {
			if(oldtelNumber.equals(telNumber)) {
				JSONObject parseObject = get(telNumber,accessToken);
				if(parseObject.getBoolean("success")) {
					JSONObject jsonObject = returnjsonObject(member);
					JSONArray maindata = parseObject.getJSONArray("data");
					if(maindata.size()>0) {
						log.info("通过电话查询后有进入修改！");
						String openId = maindata.getJSONObject(0).getString("openId");
						log.info("openId:"+openId);
						if(member.getEnabled()) {
							log.info("启用");
							updateStatus(openId,"4",accessToken);
							V3xOrgDepartment department = orgManager.getDepartmentById(member.getOrgDepartmentId());
							String orgId = department.getDescription();//云之家部门ID
							log.info("orgId:"+orgId);
							updatePhone(openId, telNumber, accessToken);//修改电话
							if(Strings.isNotBlank(orgId)) {
								updateDeptByDeptId(openId, orgId, accessToken);//修改部门
							}
							uptMember(member,openId,accessToken,jsonObject);//电话存在就修改
						}else {
							log.info("禁用");
							updateStatus(openId,"3",accessToken);
						}
					}else {
						log.info("通过电话查询后没有进入新增！");
						addMember(member,accessToken,jsonObject);//电话存在就修改
					}
				}
			}else {
				log.info("电话不一样修改");
				if(Strings.isNotBlank(oldtelNumber)) {
					JSONObject parseObject = get(oldtelNumber,accessToken);
					if(parseObject.getBoolean("success")) {
						JSONObject jsonObject = returnjsonObject(member);
						JSONArray maindata = parseObject.getJSONArray("data");
						if(maindata.size()>0) {
							log.info("通过电话查询后有进入修改！");
							String openId = maindata.getJSONObject(0).getString("openId");
							log.info("openId:"+openId);
							if(member.getEnabled()) {
								log.info("启用");
								updateStatus(openId,"4",accessToken);
								V3xOrgDepartment department = orgManager.getDepartmentById(member.getOrgDepartmentId());
								String orgId = department.getDescription();//云之家部门ID
								log.info("orgId:"+orgId);
								updatePhone(openId, telNumber, accessToken);//修改电话
								if(Strings.isNotBlank(orgId)) {
									updateDeptByDeptId(openId, orgId, accessToken);//修改部门
								}
								uptMember(member,openId,accessToken,jsonObject);//电话存在就修改
							}else {
								log.info("禁用");
								updateStatus(openId,"3",accessToken);
							}
						}else {
							log.info("通过电话查询后没有进入新增！");
							addMember(member,accessToken,jsonObject);//电话存在就修改
						}
					}
				}else {
					JSONObject parseObject = get(telNumber,accessToken);
					if(parseObject.getBoolean("success")) {
						JSONObject jsonObject = returnjsonObject(member);
						JSONArray maindata = parseObject.getJSONArray("data");
						if(maindata.size()>0) {
							log.info("通过电话查询后有进入修改！");
							String openId = maindata.getJSONObject(0).getString("openId");
							log.info("openId:"+openId);
							if(member.getEnabled()) {
								log.info("启用");
								updateStatus(openId,"4",accessToken);
								V3xOrgDepartment department = orgManager.getDepartmentById(member.getOrgDepartmentId());
								String orgId = department.getDescription();//云之家部门ID
								log.info("orgId:"+orgId);
								updatePhone(openId, telNumber, accessToken);//修改电话
								if(Strings.isNotBlank(orgId)) {
									updateDeptByDeptId(openId, orgId, accessToken);//修改部门
								}
								uptMember(member,openId,accessToken,jsonObject);//电话存在就修改
							}else {
								log.info("禁用");
								updateStatus(openId,"3",accessToken);
							}
						}else {
							log.info("通过电话查询后没有进入新增！");
							addMember(member,accessToken,jsonObject);//电话存在就修改
						}
					}
				}
			}
		}else {
			log.info("电话为空！");
		}
    	
	}
	/**
	 * 删除人员监听
	 * @param event
	 * @throws Exception 
	 */
	@ListenEvent(event= DeleteMemberEvent.class,async=true)
	public void onDeleteMember(DeleteMemberEvent event) throws Exception{
		log.info("进入人员删除！");
		String accessToken = resService.getToken();
    	log.info("accessToken:"+accessToken);
		V3xOrgMember member = event.getMember();
		String telNumber = member.getTelNumber();
		JSONObject jsonObject = new JSONObject();
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add(telNumber);
		jsonObject.put("type", 0);
		jsonObject.put("array", arrayList);
		Map<String, String> selectparams=new HashMap<String, String>();
		selectparams.put("eid", EID);
		selectparams.put("data", jsonObject.toString());
		selectparams.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("selectparams:"+JSONObject.toJSONString(selectparams));
		String url="https://yunzhijia.com/gateway/openimport/open/person/get?accessToken="+accessToken;//查询人员
		String selectback = HttpUtil.sendPost(url, selectparams);
		JSONObject parseObject = JSONObject.parseObject(selectback);
		if(parseObject.getBoolean("success")) {
			JSONArray dataArray = parseObject.getJSONArray("data");
			ArrayList<String> openIds = new ArrayList<String>();
			for(int i=0;i<dataArray.size();i++) {
				openIds.add(dataArray.getJSONObject(i).getString("openId"));
			}
			JSONObject backObject = new JSONObject();
			backObject.put("openIds", openIds);
			Map<String, String> params=new HashMap<String, String>();
			params.put("eid", EID);
			params.put("data", backObject.toString());
			params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
			log.info("params:"+JSONObject.toJSONString(params));
			String deleteurl="https://yunzhijia.com/gateway/openimport/open/person/delete?accessToken="+accessToken;//删除人员
			String sendByHttp = HttpUtil.sendPost(deleteurl, params);
			log.info("调用后回参:"+sendByHttp);
		}
	}
	
	/**
	 * 新增部门监听
	 * @param event
	 * @throws Exception 
	 */
	@ListenEvent(event= AddDepartmentEvent.class,async=true)
	public void onAddDepartment(AddDepartmentEvent event) throws Exception{
		log.info("进入部门新增！");
		String accessToken = resService.getToken();
    	log.info("accessToken:"+accessToken);
		V3xOrgDepartment dept = event.getDept();
		V3xOrgAccount account = orgManager.getAccountById(dept.getOrgAccountId());
		String unitName=account.getName();
		ArrayList<String> departments=new ArrayList<String>();
		ArrayList<String> weights=new ArrayList<String>();
		String name = dept.getName();
		log.info("当前name："+name);
		log.info("===========================================");
		String sortId = dept.getSortId().toString();
		log.info("当前sortId："+sortId);
		log.info("===========================================");
		String wholeName = dept.getWholeName();
		log.info("当前wholeName："+wholeName);
		wholeName=unitName+"\\"+wholeName.replace(",", "\\");
		log.info("处理后wholeName："+wholeName);
		log.info("===========================================");
		departments.add(wholeName);
		weights.add(sortId);
		JSONObject backObject = new JSONObject();
		backObject.put("departments", departments);
		backObject.put("weights", weights);
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/dept/add?accessToken="+accessToken;//新增组织
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
		String orgId="";
//		70fe4c0e-fc8a-40fb-89c5-27da1b51c1f1//农机公司
//		2911c71d-bcaa-4b49-8f13-aea3e3f3f54a//新能源公司
//		bccb6dc8-29d0-44c7-bb65-3b00755e5132//泰国
//		70d17052-6f13-4a34-8dad-004bce2ed078//无锡公司
		if(dept.getOrgAccountId().toString().equals("6072530065191945756")) {
			orgId="70fe4c0e-fc8a-40fb-89c5-27da1b51c1f1";//农机公司
		}
		if(dept.getOrgAccountId().toString().equals("-6714542423148180945")) {
			orgId="70d17052-6f13-4a34-8dad-004bce2ed078";//无锡公司
		}
		if(dept.getOrgAccountId().toString().equals("3163022823878248069")) {
			orgId="bccb6dc8-29d0-44c7-bb65-3b00755e5132";//泰国公司
		}
		if(dept.getOrgAccountId().toString().equals("4642584434970083544")) {
			orgId="2911c71d-bcaa-4b49-8f13-aea3e3f3f54a";//新能源公司
		}
		String APPaccessToken = appService.getToken();
		JSONObject getsuborgs = getsuborgs(EID, orgId, APPaccessToken);
		JSONArray jsonArray = getsuborgs.getJSONArray("data");
		for(int i=0;i<jsonArray.size();i++) {
			String deptId = jsonArray.getJSONObject(i).getString("orgId");
			if(jsonArray.getJSONObject(i).getString("name").equals(dept.getName())) {
				for(V3xOrgDepartment department:orgManager.getDepartmentsByName(jsonArray.getJSONObject(i).getString("name"), dept.getOrgAccountId())) {
					department.setDescription(deptId);
					orgManagerDirect.updateDepartment(department);
				}
			}
		}
	}
	/**
	 * 修改部门监听
	 * @param event
	 * @throws Exception 
	 */
	@ListenEvent(event= UpdateDepartmentEvent.class,async=true)
	public void onUpdateDepartment(UpdateDepartmentEvent event) throws Exception{
		log.info("进入修改部门！");
		String accessToken = resService.getToken();
    	log.info("accessToken:"+accessToken);
    	V3xOrgDepartment dept = event.getDept();
    	V3xOrgDepartment oldDept = event.getOldDept();
    	JSONObject jsonObject = new JSONObject();
		JSONArray departments = new JSONArray();
		jsonObject.put("orgId", dept.getDescription());
		jsonObject.put("todepartment", dept.getName());
		departments.add(jsonObject);
		JSONObject backObject = new JSONObject();
		backObject.put("departments", departments);
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/dept/updateById?accessToken="+accessToken;//修改组织
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
		String deptfa = dept.getPath().substring(0,dept.getPath().length()-4);
		String olddeptfa = oldDept.getPath().substring(0,oldDept.getPath().length()-4);
    	if(!deptfa.equals(olddeptfa)) {
    		moveOrg(dept,oldDept,accessToken);
    	}
		
	}
	public void moveOrg(V3xOrgDepartment dept,V3xOrgDepartment oldDept,String accessToken) throws Exception{
		String moveToOrgId = oldDept.getDescription();
		V3xOrgDepartment departmentByPath = orgManager.getDepartmentByPath(dept.getPath().substring(0,dept.getPath().length()-4));
		String orgId=departmentByPath.getDescription();
		log.info("moveToOrgId:"+moveToOrgId);
		log.info("orgId:"+orgId);
		if(departmentByPath.getId().toString().equals("6072530065191945756")) {
			orgId="70fe4c0e-fc8a-40fb-89c5-27da1b51c1f1";//农机公司
		}
		if(departmentByPath.getId().toString().equals("-6714542423148180945")) {
			orgId="70d17052-6f13-4a34-8dad-004bce2ed078";//无锡公司
		}
		if(departmentByPath.getId().toString().equals("3163022823878248069")) {
			orgId="bccb6dc8-29d0-44c7-bb65-3b00755e5132";//泰国公司
		}
		if(departmentByPath.getId().toString().equals("4642584434970083544")) {
			orgId="2911c71d-bcaa-4b49-8f13-aea3e3f3f54a";//新能源公司
		}
		JSONObject backObject = new JSONObject();
		backObject.put("orgId", moveToOrgId);//待挪动部门ID
		backObject.put("moveToOrgId", orgId);//挪动到的部门ID
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/dept/moveOrg?accessToken="+accessToken;//修改组织
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
	}
	/**
	 * 删除部门监听
	 * @param event
	 * @throws Exception 
	 */
	@ListenEvent(event= DeleteDepartmentEvent.class,async=true)
	public void onDeleteDepartment(DeleteDepartmentEvent event) throws Exception{
		log.info("进入删除部门！");
		String accessToken = resService.getToken();
    	log.info("accessToken:"+accessToken);
		V3xOrgDepartment dept = event.getDept();
		ArrayList<String> departments=new ArrayList<String>();
		departments.add(dept.getDescription());
		JSONObject backObject = new JSONObject();
		backObject.put("departments", departments);
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/dept/deleteById?accessToken="+accessToken;//删除组织
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
	}
	/**
	 * 禁用启用人员
	 * @param event
	 */
	public static void updateStatus(String openId,String type,String accessToken) {
		JSONObject Object= new JSONObject();
		Object.put("openId", openId);
		Object.put("type", type);
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(Object);
		JSONObject backObject = new JSONObject();
		backObject.put("persons", jsonArray);
		log.info("data："+backObject.toString());
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/person/updateStatus?accessToken="+accessToken;//新增人员
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
	}
	/**
	 * 修改电话
	 * @param event
	 */
	public void updatePhone(String openId,String telNumber,String accessToken) {
		JSONObject object = new JSONObject();
		object.put("openId", openId);
		object.put("phone", telNumber);//电话
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(object);
		JSONObject backObject = new JSONObject();
		backObject.put("persons", jsonArray);
		log.info("data："+backObject.toString());
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/person/updatePhone?accessToken="+accessToken;//修改电话
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
	}
	/**
	 * 根据组织id批量更新人员组织
	 * @param event
	 */
	public void updateDeptByDeptId(String openId,String orgId,String accessToken) {
		JSONObject object = new JSONObject();
		object.put("openId", openId);
		object.put("orgId", orgId);//组织ID
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(object);
		JSONObject backObject = new JSONObject();
		backObject.put("persons", jsonArray);
		log.info("data："+backObject.toString());
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/person/updateDeptByDeptId?accessToken="+accessToken;//根据组织id批量更新人员组织
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
	}
	/**
	 * 查询人员
	 * @param event
	 * @return 
	 */
	public static JSONObject get(String telNumber,String accessToken) {
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add(telNumber);
		JSONObject jsonObjectamin = new JSONObject();
		jsonObjectamin.put("type",0);
		jsonObjectamin.put("array",arrayList);
		String mainurl="https://yunzhijia.com/gateway/openimport/open/person/get?accessToken="+accessToken;//查询人员
		Map<String, String> mainparams=new HashMap<String, String>();
		mainparams.put("eid", EID);
		mainparams.put("data", jsonObjectamin.toString());
		mainparams.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(mainparams));
		String Http = HttpUtil.sendPost(mainurl, mainparams);
		log.info("调用后回参:"+Http);
		JSONObject parseObject = JSONObject.parseObject(Http);
		return parseObject;
	}
	/**
	 * 返回处理后的数据
	 * @param event
	 * @return 
	 * @throws BusinessException 
	 */
	public JSONObject returnjsonObject(V3xOrgMember member) throws BusinessException {
		JSONArray deptarray = MyUtils.getOrgDepartments(member.getOrgAccountId().toString());
        V3xOrgAccount account = orgManager.getAccountById(member.getOrgAccountId());
		log.info("部门回参："+deptarray.toString());
		JSONObject jsonObject = new JSONObject();
		for(int i=0;i<deptarray.size();i++) {
			log.info("===========================================");
			String wholeName = deptarray.getJSONObject(i).getString("wholeName");
			log.info("当前wholeName："+wholeName);
			wholeName=account.getName()+"\\"+wholeName.replace(",", "\\");
			log.info("处理后wholeName："+wholeName);
			log.info("===========================================");
			jsonObject.put(deptarray.getJSONObject(i).getString("path"), wholeName);
		}
		return jsonObject;
	}
	
	/**
	 * 查询人员
	 * @param event
	 * @return 
	 */
	public static void updateDept(String department,String openId,String accessToken) {
		JSONObject object = new JSONObject();
		object.put("openId", openId);
		object.put("department", department);//部门
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(object);
		JSONObject backObject = new JSONObject();
		backObject.put("persons", jsonArray);
		log.info("data："+backObject.toString());
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/person/updateDept?accessToken="+accessToken;//修改部门
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
	}
	
	public static String SetThirdpartyUser(String openId,String phone) {
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("registerCode", OAAPPCODE);
		jsonObject.put("thirdUserId", openId);
		jsonObject.put("thirdMobile", phone);
		jsonObject.put("thirdLoginName", phone);
		jsonArray.add(jsonObject);
		CTPRestClient client = getClient();
		JSONObject Object = new JSONObject();
		Object.put("userlist", jsonArray);
		log.info("发送参数:"+Object.toString());
		String resultMap = client.post("thirdpartyUserMapper/binding", Object, String.class);
		log.info("返回结果:"+resultMap);
		return resultMap;
		
	}
	
	/**
	 * 获取接口client对象
	 * @return
	 * @time   2021年8月19日 下午2:29:31
	 */
	public static CTPRestClient getClient() {
		String oaIp = AppContext.getSystemProperty("auth.oaip");
		String rest = AppContext.getSystemProperty("auth.restName");
		String restpass = AppContext.getSystemProperty("auth.restPsw");
		// 获取 CTPServiceClientManager对象
		CTPServiceClientManager clientManager = CTPServiceClientManager.getInstance(oaIp);
		// 通过 OA ip 获取 CTPRestClient对象
		CTPRestClient client = clientManager.getRestClient();
		// 绑定rest 用户名和密码
		client.authenticate(rest, restpass);
		// 绑定登录名 (此登录名必须有相关的接口权限)
		client.bindUser(AppContext.getSystemProperty("auth.bindUser"));
		return client;
	}
	
	/**
	 * 查询单位下所有部门
	 * @param event
	 * @return 
	 */
	public static JSONObject getsuborgs(String eid,String orgId,String accessToken) {
		JSONObject jsonObjectamin = new JSONObject();
		jsonObjectamin.put("eid",eid);
		jsonObjectamin.put("orgId",orgId);
		String mainurl="https://yunzhijia.com/gateway/opendata-control/data/getsuborgs?accessToken="+accessToken;//查询人员
		Map<String, String> mainparams=new HashMap<String, String>();
		mainparams.put("eid", EID);
		mainparams.put("orgId",orgId);
//		mainparams.put("data", jsonObjectamin.toString());
//		mainparams.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(mainparams));
		String Http = HttpUtil.sendPost(mainurl, mainparams);
		log.info("调用后回参:"+Http);
		JSONObject parseObject = JSONObject.parseObject(Http);
		return parseObject;
	}
	public static void main(String[] args) {
		String accessToken = resService.getToken();
    	log.info("accessToken:"+accessToken);
		ArrayList<String> departments=new ArrayList<String>();
		departments.add("");
		JSONObject backObject = new JSONObject();
		backObject.put("departments", departments);
		log.info("backObject"+backObject.toString());
		String url="https://yunzhijia.com/gateway/openimport/open/dept/deleteById?accessToken="+accessToken;//删除组织
		Map<String, String> params=new HashMap<String, String>();
		params.put("eid", EID);
		params.put("data", backObject.toString());
		params.put("nonce", RandomStringUtils.randomAlphanumeric(16));
		log.info("params:"+JSONObject.toJSONString(params));
		String sendByHttp = HttpUtil.sendPost(url, params);
		log.info("调用后回参:"+sendByHttp);
	}
}

